/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Image, Alert, Tooltip, Modal, message, Button, Typography } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { paymentorder, companydetail } from '@/services/business';
import { search } from '@/services/basic';
import { customer } from '@/services/customer';
import { payment_cycle, payment } from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import moment from 'moment';
import CompanyName from '@/components/CompanyName';


// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input
const { Paragraph } = Typography;
let defaultFields = {
  total: {
    value: null,
    type: 'inputnumber',
    title: '累计收款',
    name: ['total'],
    required: true,
    disabled: true,
  },
  unit_price: {
    value: null,
    type: 'inputnumber',
    title: '月收费',
    name: ['unit_price'],
    required: true,
  },
  receivable: {
    value: null,
    type: 'inputnumber',
    title: '应收款',
    name: ['receivable'],
    required: true,
  },
  actual_receive: {
    value: null,
    type: 'inputnumber',
    title: '实际收款',
    name: ['actual_receive'],
    required: true,
  },
  payment_id: {
    value: null,
    type: 'select',
    title: '收款方式',
    name: ['payment_id'],
    options: {
      database: payment,
      params: {
        is_all: 1,
      },
    },
    required: true,
  },
  payment_cycle_id: {
    value: null,
    type: 'select',
    title: '收款周期',
    name: ['payment_cycle_id'],
    options: {
      database: payment_cycle,
      params: {
        is_all: 1,
      },
    },
    required: true,
  },
  payment_type: {
    value: null,
    type: 'select',
    title: '收款类型',
    name: ['payment_type'],
    options: [
      {
        label: '全款',
        value: 'full',
      },
      {
        label: '定金',
        value: 'deposit',
      },
      {
        label: '尾款',
        value: 'balance',
      },
    ],
    required: true,
  },
  service: {
    value: null,
    type: 'daterange',
    title: '服务区间',
    name: ['service'],
    required: true,
  },
  payment_time: {
    value: null,
    type: 'datepicker',
    title: '收款日期',
    name: ['payment_time'],
    required: true,
    disabledDate: (current) => {
      return current && current > moment().endOf('day');
    },
    options: {
      database: customer,
      params: { is_all: 1 },
    },
  },
  next_order_time_type: {
    value: null,
    type: 'select',
    title: '收款单生成日',
    name: ['next_order_time_type'],
    options: [
      {
        label: '期初',
        value: 'start',
      },
      {
        label: '期末',
        value: 'end',
      },
    ],
    required: true,
  },
  not_count_service: {
    value: null,
    type: 'daterange',
    title: '未结算服务区间',
    name: ['not_count_service'],
    required: true,
  },
  balance: {
    value: undefined,
    type: 'inputnumber',
    title: '未结算的金额',
    name: ['balance'],
    required: true,
  },
};

let valueEnum = {
    cache: {
      text: '暂存',
    },
    stalled: {
      text: '未开始',
    },
    dispatching: {
      text: '会计调度中',
    },
    dispatch_refuse: {
      text: '会计调度拒绝',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    account_cache: {
      text: '记账会计暂存',
    },
    completed: {
      text: '已完成',
    },
  },
  valueEnums = {
    cache: {
      text: '待激活',
      status: 'error',
    },
    cashiering: {
      text: '出纳审核中',
    },
    cashier_refuse: {
      text: '出纳拒绝',
    },
    accounting: {
      text: '会计审核中',
    },
    account_refuse: {
      text: '会计拒绝',
    },
    completed: {
      text: '已完成',
    },
  };
function Reaccount(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [vis, cvis] = useState(false),
    [fields, cf] = useState(defaultFields),
    [sd, csd] = useState(false),
    [sds, csds] = useState(false),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '本期收费单号',
      dataIndex: 'settle_id',
      key: 'settle_id',
      width: 100,
      copyable: true,
      search: false,
      render: (_, row) => (
        <span>{row.settle_id ? (Array(5).join(0) + row.settle_id).slice(-5) : '-'}</span>
      ),
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      copyable: true,
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '业务类型',
      dataIndex: 'service_type_name',
      key: 'service_type_name',
      search: false,
    },
    {
      title: '应收款',
      dataIndex: 'receivable',
      key: 'receivable',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '服务开始时间',
      dataIndex: 'service_start_time',
      key: 'service_start_time',
      width: 100,
      search: false,
    },
    {
      title: '服务结束时间',
      dataIndex: 'service_end_time',
      key: 'service_end_time',
      search: false,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '支付周期',
      dataIndex: 'payment_cycle_name',
      key: 'payment_cycle_name',
      search: false,
    },
    {
      title: '周期月数',
      dataIndex: 'cycle_num',
      key: 'cycle_num',
      search: false,
    },
    {
      title: '支付类型',
      dataIndex: 'payment_type',
      key: 'payment_type',
      valueType: 'select',
      options: [
        {
          id: 'full',
          name: '全款',
        },
        {
          id: 'deposit',
          name: '定金',
        },
        {
          id: 'balance',
          name: '尾款',
        },
      ],
      valueEnum: {
        full: {
          text: '全款',
        },
        deposit: {
          text: '定金',
        },
        balance: {
          text: '尾款',
        },
      },
    },
    {
      title: '收款日期',
      dataIndex: 'payment_time',
      key: 'payment_time',
    },
    {
      title: '实际收款',
      dataIndex: 'actual_receive',
      key: 'actual_receive',
    },
    {
      title: '收款方式',
      dataIndex: 'payment_name',
      key: 'payment_id',
      valueType: 'select',
      options: {
        database: payment,
        params: {
          is_all: 1,
        },
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      search: false,
    },
    {
      title: '是否登账',
      dataIndex: 'is_register',
      key: 'is_register',
      width: 100,
      valueType: 'select',
      options: [
        {
          label: '已登账',
          value: true,
        },
        {
          label: '未登账',
          value: false,
        },
      ],
      render: (dom, row) => (
        <div style={{ color: row?.is_register ? '#1890ff' : '#ff4800' }}>
          {row?.is_register ? '已登账' : '未登账'}
        </div>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          disabled={record?.is_register}
          onClick={() => {
            if (record?.is_register) {
              return;
            }
            companydetail({ id: record.company_id }).then((res) => {
              cvs(true);
              cf((fields) => {
                return {
                  is_register: {
                    value: true,
                    type: 'radio',
                    title: '是否登账',
                    name: ['is_register'],
                    required: false,
                    options: [
                      {
                        label: '否',
                        value: false,
                      },
                      {
                        label: '是',
                        value: true,
                      },
                    ],
                    col: { span: 24 },
                  },
                };
              });
              ciftype({
                val: 'refuse',
                title: '确认登账',
                id: record.id,
                curitems: res.data,
                curitem: record,
              });
            });
          }}
        >
          登账
        </a>,
        <a
          onClick={() => {
            companydetail({ id: record.company_id }).then((res) => {
              if (res?.data) {
                let copytext = `${res.data.area_name} \n${res.data.name} \n${record.payment_name}`;

                if (record.service_start_time) {
                  copytext += ` \n${record.service_start_time}`;
                }

                if (record.service_end_time) {
                  copytext += ` \n${record.service_end_time}`;
                }

                if (record.is_first) {
                  copytext += ` \n${record.user_name}`;
                }

                Modal.info({
                  title: '请复制登账信息',
                  closable: true,
                  content: (
                    <div>
                      <div style={{ lineHeight: 2 }}>
                        区域:{res.data.area_name}
                        <br />
                        客户名称:{res.data.name}
                        <br />
                        支付方式:{record.payment_name}
                        <br />
                        {record.service_start_time ? (
                          <>服务开始时间:{record.service_start_time}</>
                        ) : null}
                        <br />
                        {record.service_end_time ? (
                          <>服务结束时间:{record.service_end_time}</>
                        ) : null}
                        <br />
                        {record.is_first ? <>接单人:{record.user_name}</> : null}
                      </div>
                    </div>
                  ),
                  okText: (
                    <div
                      className="tocopy"
                      onClick={(e) => {
                        e.stopPropagation();
                        Modal.destroyAll();
                      }}
                    >
                      <Paragraph
                        copyable={{
                          text: copytext,
                          icon: [<span>一键复制</span>, <span>已复制</span>],
                          onCopy: () => {
                            Modal.destroyAll();
                          },
                        }}
                        style={{ lineHeight: 2, color: '#fff' }}
                        onClick={(e) => {
                          e.stopPropagation();
                          Modal.destroyAll();
                        }}
                      />
                    </div>
                  ),
                });
              }
            });
          }}
        >
          复制
        </a>,
      ],
    },
  ];

  const columnes = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '公司法人',
      dataIndex: 'legal_person',
      key: 'legal_person',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
      hideInTable: true,
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'enterprise_credit_code',
      key: 'enterprise_credit_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司营业执照',
      dataIndex: 'origin_url',
      key: 'origin_url',
      render: (_, row) => {
        return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url} />;
      },
      hideInTable: true,
      search: false,

    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '活动',
      dataIndex: 'activity_content',
      key: 'activity_content',
      search: false,
      hideInTable: true,
    },
    {
      title: '续单',
      dataIndex: 'is_create_order',
      key: 'is_create_order',
      search: false,
      render: (_, row) => <span>{row.is_create_order ? '是' : '否'}</span>,
    },
    {
      title: '会计流程',
      dataIndex: 'is_accountant',
      key: 'is_accountant',
      search: false,
      render: (_, row) => <span>{row.is_accountant ? '是' : '否'}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: valueEnum,
      width: 120,
      render: (dom, row) => (
        <div
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
        >
          {valueEnum[row?.status]?.text}
        </div>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            />
          );
        } else {
          return row.contracts.map((it) => {
            return <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />;
          });
        }
      },
      hideInTable: true,
    },
  ];

  let saveData = (values) => {
    let { dispatch } = props;

    if (values.is_register) {
      dispatch({
        type: 'business/set_register',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/payment_order"
        extraparams={{ status: 'completed' }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
        style={{ top: 20 }}
      >
        {iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`收款单的详细信息`}
            columns={[
              ...JSON.parse(JSON.stringify(columns)).map((it) => {
                if (it.key == 'company_name') {
                  delete it.render;
                }
                return it;
              }),
            ]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <div>
            <Alert
              message="显示/隐藏详情"
              style={{ marginBottom: 20 }}
              showIcon
              type="info"
              action={[
                <Button
                  style={{ marginRight: 10 }}
                  size="small"
                  type="primary"
                  onClick={() => {
                    csd(!sd);
                  }}
                >
                  {!sd ? '显示收款单' : '隐藏收款单'}
                </Button>,
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    csds(!sds);
                  }}
                >
                  {!sds ? '显示代账公司' : '隐藏代账公司'}
                </Button>,
              ]}
            />
            <div
              style={{
                backgroundColor: '#f9f9f9',
                padding: sd ? 12 : 0,
                paddingBottom: 0,
                borderRadius: 8,
                height: sd ? 'auto' : 0,
                transition: 'all 0.4s',
                overflow: 'hidden',
                marginBottom: 12,
              }}
            >
              <ProDescriptions
                title={`收款单的详细信息`}
                columns={[
                  ...JSON.parse(JSON.stringify(columns)).map((it) => {
                    if (it.key == 'company_name') {
                      delete it.render;
                    }
                    return it;
                  }),
                ]}
                column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
                dataSource={iftype?.curitem}
              />
            </div>

            <div
              style={{
                backgroundColor: '#f9f9f9',
                padding: sds ? 12 : 0,
                paddingBottom: 0,
                borderRadius: 8,
                height: sds ? 'auto' : 0,
                transition: 'all 0.4s',
                overflow: 'hidden',
              }}
            >
              <ProDescriptions
                title={`${iftype?.curitems?.name}的详细信息`}
                columns={[...columnes]}
                column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
                dataSource={iftype?.curitems}
              />
            </div>
            <InitForm
              fields={fields}
              submitData={(values) => {
                saveData(values);
              }}
              onChange={(changedValues, allValues) => {
                //联动操作
              }}
              submitting={
                props.loading.effects['business/accountretrys'] ||
                props.loading.effects['business/cashiersubmit'] ||
                !vs
              }
              halfsave={false}
            />
          </div>
        )}
      </Modal>

      <Modal
        maskClosable={false}
        title={iftype.title}
        visible={vis}
        onCancel={() => cvis(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        <ProDescriptions
          title={`${iftype?.curitems?.name}的详细信息`}
          columns={[...columnes]}
          column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
          dataSource={iftype?.curitems}
        />
      </Modal>
    </div>
  );
}

export default connect(({ business, loading }) => ({
  business,
  loading,
}))(Reaccount);
